from __future__ import absolute_import

from io import open
from glob import iglob

import os
import datetime
import fnmatch
import shutil
import sys
import time

# ------------------------------------------------------------------------------------------------------#

def get_year():
  """ Returns the current year. """
  return str(datetime.datetime.now().year)

# ------------------------------------------------------------------------------------------------------#

def read_file(name, normalize=True):
  """ Read a file. """
  try:
    with open(name, 'r', encoding='utf-8') as f:
      # read the data
      data = f.read()
      if normalize:
        # normalize line endings
        data = data.replace("\r\n", "\n")

      return data
  except IOError as e:
    (errno, strerror) = e.args
    sys.stderr.write('Failed to read file ' + name + ': ' + strerror)
    raise

# ------------------------------------------------------------------------------------------------------#

def write_file(name, data):
  """ Write a file. """
  try:
    with open(name, 'w', encoding='utf-8') as f:
      # write the data
      if sys.version_info.major == 2:
        f.write(data.decode('utf-8'))
      else:
        f.write(data)
  except IOError as e:
    (errno, strerror) = e.args
    sys.stderr.write('Failed to write file ' + name + ': ' + strerror)
    raise

# ------------------------------------------------------------------------------------------------------#
def make_dirs(name, quiet=True):
  """ Create the specified directory. """
  try:
    if not path_exists(name):
      if not quiet:
        sys.stdout.write('Creating ' + name + ' directory.\n')

      os.makedirs(name)
  except IOError as e:
    (errno, strerror) = e.args
    sys.stderr.write('Failed to create directory ' + name + ': ' + strerror)
    raise

# ------------------------------------------------------------------------------------------------------#
def path_exists(name):
  """ Returns true if the path currently exists. """
  return os.path.exists(name)

# ------------------------------------------------------------------------------------------------------#

def backup_file(name, quiet=True):
  """ Rename the file to a name that includes the current time stamp. """
  bak_name = name + '.' + time.strftime('%Y-%m-%d-%H-%M-%S')
  try:
    shutil.move(name, bak_name)
    if not quiet:
      sys.stdout.write('Moving ' + name + ' file.\n')
  except IOError as e:
    (errno, strerror) = e.args
    sys.stderr.write('Failed to move file from ' + name + ' to ' + bak_name + ': ' + strerror)
    raise

# ------------------------------------------------------------------------------------------------------#

def get_files(search_glob):
  """ Returns all files matching |search_glob|. """
  recursive_glob = '**' + os.path.sep
  if recursive_glob in search_glob:
    if sys.version_info >= (3, 5):
      result = iglob(search_glob, recursive=True)
    else:
      # Polyfill for recursive glob pattern matching added in Python 3.5.
      result = get_files_recursive(*search_glob.split(recursive_glob))
  else:
    result = iglob(search_glob)

  # Sort the result for consistency across platforms.
  return sorted(result)

# ------------------------------------------------------------------------------------------------------#

def get_files_recursive(directory, pattern):
  """ Returns all files in |directory| matching |pattern| recursively. """
  for root, dirs, files in os.walk(directory):
    for basename in files:
      if fnmatch.fnmatch(basename, pattern):
        filename = os.path.join(root, basename)
        yield filename

